#!/bin/bash
set -e

# 更新系统
echo "更新系统包列表..."
apt update && apt upgrade -y

# 安装基础依赖
echo "安装基础依赖..."
apt install -y \
    build-essential \
    cmake \
    git \
    libyaml-cpp-dev \
    libeigen3-dev \
    libmodbus-dev \
    libwebsockets-dev \
    pkg-config \
    linux-headers-$(uname -r)

# 安装IgH EtherCAT主站
echo "安装IgH EtherCAT主站..."
apt install -y ethercat

# 安装实时内核
echo "安装PREEMPT_RT实时内核..."
apt install -y linux-image-rt-amd64 linux-headers-rt-amd64

# 配置EtherCAT权限
echo "配置EtherCAT权限..."
groupadd ethercat
usermod -a -G ethercat $SUDO_USER
echo 'KERNEL=="EtherCAT[0-9]*", MODE="0664", GROUP="ethercat"' > /etc/udev/rules.d/99-ethercat.rules

# 配置实时权限
echo "配置实时调度权限..."
cat << EOF > /etc/security/limits.d/99-realtime.conf
@realtime - rtprio 99
@realtime - memlock unlimited
EOF

groupadd realtime
usermod -a -G realtime $SUDO_USER

echo "所有依赖安装完成，请重启系统以启用实时内核"
